package com.why.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.why.domain.Teacher;
import com.why.utils.BaseContext;
import com.why.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Resource
    private RedisTemplate<String, Teacher> redisTemplate;
    @Override // 目标资源方法运行前运行, 返回true: 放行, 放回false, 不放行
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        String url = req.getRequestURL().toString();
        log.info("请求的url: {}", url);

        // 2.获取请求头中的令牌（token）。
        String token = req.getHeader("call-name-token");
        System.out.println(token);

        // 3.判断令牌是否存在，如果不存在，返回错误结果（未登录）。
        if (!StringUtils.hasLength(token)) {
            Result error = Result.error("NOT_LOGIN");
            // 手动转换 对象--json --------> 阿里巴巴fastJSON
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return false;
        }
        Teacher teacher = redisTemplate.opsForValue().get("rh-call-name-token:" + token);
        if (Objects.isNull(teacher)) {
            Result error = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return false;
        }
        // 获取请求者ip地址
        String reqRemoteAddr = req.getRemoteAddr();
        List<Object> list = new ArrayList<>();
        list.add(teacher);
        list.add(reqRemoteAddr);
        BaseContext.setCurrentIdAndIp(list);
        return true;
    }
}
